package com.xzm.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 瞎琢磨先生 https://github.com/xiazuomo/xzm-utils.git
 * @date 2022/7/29 23:51
 */
@Slf4j
public class ListChainUtils {

    public static void main(String[] args) {
        final ListBuilder<Integer> builder = ListChainUtils.builder(getList(Integer.class))
                .add(2)
                .add(3);

        final List<Integer> endList = builder.endBuilder();
        System.out.println("endList = " + endList);

    }

    private static <T> ArrayList<T> getList(Class<T> clazz) {
        return new ArrayList<T>();
    }

    /*private static List<String> getList2() {
            // 注意在 new 的时候，要将具体的泛型类型设置上
            List<String> list = new ArrayList<String>() {{
                // 注意是2层的{{
                // add直接使用，不要 list.add(),因为此时list还没有初始化完，会空指针异常
                add("1");
                add("2");
                add("3");
            }};
            return list;
        }*/

    public static <E> ListBuilder<E> builder(List<E> list) {
        return ListBuilder.builder(list);
    }

    public static class ListBuilder<E> {

        private final List<E> list;

        private ListBuilder(List<E> list) {
            this.list = list;
        }

        public static <E> ListBuilder<E> builder(List<E> list) {
            return new ListBuilder<E>(list);
        }

        public List<E> endBuilder() {
            return list;
        }

        public ListBuilder<E> add(E e) {
            list.add(e);
            return this;
        }

    }
}
